package com.miracle.java2110;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

/**
 * @ClassName : QiniuUtils
 * @Author : glls
 * @Date: 2021/11/5 14:38
 * @Description :
 */
public class QiniuUtilsGuest {

    public static String accessKey="OegPqYnwOUxH_oikj3WwTyDCMQ5h3FqlYAzXQiW9";
    public static String secretKey="Y7Mt4LOZI1lDpkWre-vyu_Uy-s_h-CW206F-Mapz";
    public static String bucket="bk-8";


    public static void uploadLoclFile2Qiniu(String localFilePath,String uploadFileName){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());

        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);

        String upToken = auth.uploadToken(bucket);
        Response response = null;
        try {
            response = uploadManager.put(localFilePath, uploadFileName, upToken);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

        } catch (QiniuException e) {
            Response r = e.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }



    }


    public static void uploadBytes2Qiniu(byte[] bytes,String uploadFileName){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());

        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);

        String upToken = auth.uploadToken(bucket);
        Response response = null;
        try {
            response = uploadManager.put(bytes, uploadFileName, upToken);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

        } catch (QiniuException e) {
            Response r = e.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }



    public static void main(String[] args) throws IOException {

        byte[] bytes = FileUtils.readFileToByteArray(new File("E:\\img\\test\\16.png"));

        uploadBytes2Qiniu(bytes,"16.png");
    }
}
